<?php

namespace app\admin\controller\goods;

use app\common\controller\Backend;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 商品
 *
 * @icon fa fa-circle-o
 */
class Seckill extends Backend
{

    /**
     * Goods模型对象
     * @var \app\admin\model\goods\Seckill
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\goods\Seckill;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = false;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $list = $this->model
                    ->alias('g')
                    ->join('goods_seckill gs','g.id = gs.good_id')
                    ->field('g.id,g.name,g.money,g.cate_id,g.status,g.num,g.image,gs.create_time,g.cate_pid')
                    ->where($where)
                    ->order('create_time desc')
                    ->paginate($limit)->each(function($item,$key){
                        $cate_title    = Db::name('cate_goods')->where('id',$item['cate_pid'])->field('pid,title')->find();
                        $cate_name     = Db::name('cate_goods')->where('id',$item['cate_id'])->value('title');
                        // $cate_title    = Db::name('cate_goods')->where('id',$item['cate_id'])->field('pid,title')->find();
                        // $cate_name     = Db::name('cate_goods')->where('id',$cate_title['pid'])->value('title');
                        // $item['title'] = $cate_name . ' L__ ' . $cate_title['title'];
                        if($cate_name)
                        {
                            $item['title'] = $cate_title['title']. ' L__ ' . $cate_name;
                        }else{
                            $item['title'] = $cate_title['title'];
                        }
                        switch($item['status'])
                        {
                            case 1;
                                $item['status'] = '是';
                                break;
                            case 2;
                                $item['status'] = '否';
                                break;
                        }
                        return $item;
                });

            foreach ($list as $row) {
                $row->visible(['id','name','cate_id','image','num','money','status','title','create_time']);
                
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                $data['name']      = $params['name'];
                $data['image']     = $params['image'];
                $data['start_time']     = strtotime($params['start_time']);// 开始时间
                $data['end_time']       = strtotime($params['end_time']);// 结束时间
//                $data['num']       = $params['num'];
                $data['item']      = $params['basic'];
                $data['desc']      = $params['desc'];
//                $data['cate_pid']  = $params['cate_id'];
//                $data['cate_id']   = $params['cate_ids'];
                $data['activity']       = $params['activity'];// 活动状态
                $data['create_time']  = time();

                // 获取修改前的商品信息
                $goods = Db::name('goods')->where('id',$params['id'])->value('item');
                $goods = json_decode($goods,true);
                $nums = $num = [];
                foreach($goods as $val)
                {
                    $nums[] = $val['stock'];
                }
                // 获取修改后的商品信息
                $item = json_decode($params['basic'],true);
                foreach($item as $val)
                {
                    $num[] = $val['stock'];
                }
                $nums = array_sum($nums);
                $num  = array_sum($num);

                // 链接redis
                // $redis = new \Redis();
                // $redis->connect('127.0.0.1', 6379);
                
                // $key = 'list_seckill_goods_id_'.$params['id'];

                // // 删除key
                // $redis->del($key);
                // //
                // for($i = 1; $i <= $num; $i++) {
                //     $redis->lpush($key, 1);
                // }
                
                $res = Db::name('goods')->where('id',$params['id'])->update($data);
                if($res)
                {
                    $this->success();
                }else{
                    $this->error(__('修改失败'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if($row['cate_id'])
        {
            $cates = Db::name('cate_goods')->where('id',$row['cate_id'])->field('id,title')->find();
        }else{
            $cates = "";
        }
        $this->view->assign('cate',Db::name('cate_goods')->where(['pid'=>['=',0]])->field('id,title')->select());
        $this->view->assign('cates',$cates);
        $this->view->assign("row", $row);
        $this->view->assign('item',$row['item']);
        return $this->view->fetch();
    }



    /**
     * 添加
     */
    public function add()
    {
        
        if ($this->request->isPost()) {
            $params = $this->request->post('row/a');

            if ($params) {

                // 获取商品信息
                $item = Db::name('goods')->where('id',$params['id'])->value('item');
                $item = json_decode($item,true);
                // 商品id 库存
                $num  = [];
                foreach($item as $val)
                {
                    $num[] = $val['stock'];
                }
                $num = array_sum($num);

                $data['start_time']     = strtotime($params['start_time']);// 开始时间
                $data['end_time']       = strtotime($params['end_time']);// 结束时间
                $data['activity']       = $params['activity'];// 活动状态
                $data['type']           = 1;// 活动状态
                $data['update_time']    = time();// 活动状态
                if(!$data['start_time'])  $this->error(__('请选择开始时间'));
                if(!$data['end_time'])    $this->error(__('请选择结束时间'));

                $res = Db::name('goods')->where('id',$params['id'])->update($data);
                if(Db::name('goods_seckill')->where('good_id',$params['id'])->count() == 0)
                {
                    Db::name('goods_seckill')->insert(['good_id'=>$params['id'],'create_time'=>time()]);
                }

                // $redis = new \Redis();
                // $redis->connect('127.0.0.1', 6379);

                // // 商品id
                // $key = 'list_seckill_goods_id_'.$params['id'];

                // //防止对已经设置过的商品库存进行覆盖
                // if(!empty($redis->llen($key))) {
                //     return '已经设置了库存';
                // }

                // // 初始化缓存，删除抢购用户id队列key和成功信息保存key，这个是抢购时生成的，防止错乱，初始化删除
                // $userListKey = 'user_goods_id_'.$params['id'];
                // $redis->command('del', [$userListKey, 'success']);

                // // 将商品存入Redis链表中
                // for($i = 1; $i <= $num; $i++) {
                //     $redis->lpush($key, 1);
                // }

                if($res)
                {
                    $this->success();
                }else{
                    $this->error(__('添加失败'));
                }
            }

            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign('cate',Db::name('cate_goods')->where(['pid'=>['>',0]])->field('id,title')->select());
        $goods = Db::name('goods')->where('status',1)->field('id,name')->select();
        $this->assign('goods',$goods);
        return $this->view->fetch();
    }


    // 商品分类
    public function category()
    {
        $pid = $this->request->get('cate_id', '');
        $categorylist = Db::name('cate_goods')->where(['pid'=>$pid])->field('id as value,title as name')->order('id desc')->select();
        $this->success('', '', $categorylist);
    }


    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        if ($ids) {
           $res = Db::name('goods_seckill')->where('good_id',$ids)->delete();
           if($res)
           {
               $this->success('删除成功');
           }else{
               $this->error('删除失败');
           }
        }
        $this->error(__('Parameter %s can not be empty', 'ids'));
    }

}
